package com.xj.zookeeper.framework;

import org.apache.log4j.Logger;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Author: xiajun
 * Date: 2014-11-13
 * Time: 11:29:00
 * 执行监听回调函数
 */
public class ListenerProcessPool {
    private final static Logger log = Logger.getLogger(ListenerProcessPool.class);
    private static ExecutorService processPool;
    public static int listenerSize = 2;

    public static void init() {
        synchronized (ListenerProcessPool.class) {
            if (processPool == null) {
                processPool = Executors.newFixedThreadPool(listenerSize, new ListenerProcessFactory());
            }
        }
    }

    /**
     * 回调监听函数
     *
     * @param manage 监听管理对象
     */
    public static void invoker(final ListenerManager manage) {
        if (processPool == null) {
            init();
        }
        processPool.submit(new Runnable() {
            @Override
            public void run() {
                if (manage != null) {
                    if (manage.getListener() != null) {
                        try {
                            manage.getListener().listen(manage.getClient(), manage.getEventType(), manage.getData());
                        } catch (Exception e) {
                            log.error("", e);
                        }
                    }
                }
            }
        });
    }

}

class ListenerProcessFactory implements ThreadFactory {
    private AtomicInteger seq = new AtomicInteger(0);

    public Thread newThread(Runnable r) {
        Thread t = new Thread(r);
        t.setDaemon(true);
        t.setName("zkClient-listener-process-" + seq.getAndIncrement());
        return t;
    }
}